package com.jusfoun.communication.controller;

import com.jusfoun.communication.model.AppInfo;
import com.jusfoun.communication.service.AutoReplyService;
import com.jusfoun.communication.service.ManageService;
import com.jusfoun.communication.service.MessageService;
import com.jusfoun.communication.service.UserService;
import com.jusfoun.communication.util.PageInfo;
import com.jusfoun.communication.util.PageVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 页面controller
 *
 * @author player six
 * @email jslcylcy@163.com
 * @create 2017-12-05 10:49
 **/
@Controller
@ApiIgnore
public class IndexController {

    private static final Logger logger = LoggerFactory.getLogger(IndexController.class);

    @Autowired
    private ManageService manageService;

    @Autowired
    private UserService userService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private AutoReplyService autoReplyService;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private HttpServletRequest request;

    @Value("${admin.username}")
    private String adminUserName;

    @Value("${admin.password}")
    private String adminPassword;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public String index() {
        return "redirect:/index";
    }

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index2() {
        return "index";
    }

    @RequestMapping(value = "/index/login")
    public String login(@RequestParam(value = "username", required = false) String userName, @RequestParam(value = "password", required = false) String password) {
        if (adminUserName.equals(userName) && adminPassword.equals(password)) {
            request.getSession().setAttribute("user", userName);
            return "redirect:/index";
        }
        return "login";
    }

    /**
     * app管理
     *
     * @return
     */
    @RequestMapping(value = "/index/app")
    public ModelAndView indexApp(PageVo pageVo) {
        return new ModelAndView("app/list").addObject("pageInfo", manageService.list(pageVo.getPage(), pageVo.getRows()));
    }


    /**
     * 消息管理
     *
     * @return
     */
    @RequestMapping(value = "/index/message")
    public ModelAndView indexMessage(PageVo pageVo, String appId, String userName) {
        ModelAndView modelAndView = new ModelAndView("message/list");
        List<AppInfo> appInfoList = manageService.listAll();
        modelAndView.addObject("appInfoList", appInfoList);
        if (!appInfoList.isEmpty()) {
            if (StringUtils.isBlank(appId)) {
                appId = appInfoList.get(0).getAppId();
            }
            modelAndView.addObject("appId", appId);

            List<String> userList = userService.listAllByAppId(appId);
            modelAndView.addObject("userList", userList);
            if (userList.isEmpty()) {
                modelAndView.addObject("pageInfo", new PageInfo<>());
                modelAndView.addObject("userName", null);
            } else {
                if (StringUtils.isBlank(userName)) {
                    userName = userList.get(0);
                }
                modelAndView.addObject("userName", userName);
                modelAndView.addObject("pageInfo", messageService.listMessage(appId, userName, pageVo.getPage(), pageVo.getRows(), false, null, null));
            }
        } else {
            modelAndView.addObject("appId", null);
            modelAndView.addObject("userList", new ArrayList<>());
            modelAndView.addObject("userName", null);
            modelAndView.addObject("pageInfo", new PageInfo<>());
        }
        return modelAndView;
    }


    /**
     * 用户管理
     *
     * @return
     */
    @RequestMapping(value = "/index/user")
    public ModelAndView indexUser(PageVo pageVo, String appId) {
        ModelAndView modelAndView = new ModelAndView("user/list");
        List<AppInfo> appInfoList = manageService.listAll();
        modelAndView.addObject("appInfoList", appInfoList);
        if (!appInfoList.isEmpty()) {
            if (StringUtils.isBlank(appId)) {
                appId = appInfoList.get(0).getAppId();
            }
            modelAndView.addObject("pageInfo", userService.listUsers(appId, pageVo.getPage(), pageVo.getRows()));
            modelAndView.addObject("appId", appId);
        } else {
            modelAndView.addObject("pageInfo", new PageInfo<>());
            modelAndView.addObject("appId", null);
        }
        return modelAndView;
    }

    /**
     * 自动回复管理
     *
     * @return
     */
    @RequestMapping(value = "/index/autoreply")
    public ModelAndView indexAutoreply(PageVo pageVo, String appId) {
        ModelAndView modelAndView = new ModelAndView("autoreply/list");
        List<AppInfo> appInfoList = manageService.listAll();
        modelAndView.addObject("appInfoList", appInfoList);
        if (!appInfoList.isEmpty()) {
            if (StringUtils.isBlank(appId)) {
                appId = appInfoList.get(0).getAppId();
            }
            modelAndView.addObject("pageInfo", autoReplyService.list(appId, pageVo));
            modelAndView.addObject("appId", appId);
            modelAndView.addObject("useAutoReply", autoReplyService.isUseAutoReply(appId));
            modelAndView.addObject("autoReplyBegin", autoReplyService.getBeginTime(appId));
            modelAndView.addObject("autoReplyEnd", autoReplyService.getEndTime(appId));
        } else {
            modelAndView.addObject("pageInfo", new PageInfo<>());
            modelAndView.addObject("appId", null);
            modelAndView.addObject("useAutoReply", false);
            modelAndView.addObject("autoReplyBegin", "");
            modelAndView.addObject("autoReplyEnd", "");
        }


        return modelAndView;
    }

    /**
     * 下载文件
     *
     * @return
     */
    @RequestMapping(value = "/index/download-page", method = RequestMethod.GET)
    public String download() {
        return "download";
    }

    /**
     * 下载文件
     *
     * @param fileName
     * @param url
     * @return
     */
    @RequestMapping(value = "/index/download", method = RequestMethod.GET)
    @ResponseBody
    public void download(String fileName, String url) {
        logger.info("下载文件:" + url);
        // 需要对url进行编码,默认情况下，只编码最后一个 / 之后的内容
        int index = url.lastIndexOf("/") + 1;
        this.response.reset();
        this.response.setContentType("multipart/form-data");
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        try {
            url = url.substring(0, index) + URLEncoder.encode(url.substring(index), "utf-8");
            url = url.trim().replaceAll("\\+", "%20");
            this.response.setHeader("Content-Disposition",
                    "attachment;fileName=" + processFileName(this.request, fileName));
            URL url1 = new URL(url);
            conn = (HttpURLConnection) url1.openConnection();
            inputStream = conn.getInputStream();
            ServletOutputStream out = this.response.getOutputStream();
            IOUtils.copy(inputStream, out);
            out.flush();
        } catch (IOException e) {
            logger.error("下载模板文件出错", e);
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.error("下载模板文件出错", e);
                }
            }
            if (null != conn) {
                try {
                    conn.disconnect();
                } catch (Exception e) {
                    logger.error("下载模板文件出错", e);
                }
            }
        }
    }

    /**
     * @Title: processFileName
     * @Description: ie, chrom, firfox下处理文件名显示乱码
     */
    public String processFileName(HttpServletRequest request,
                                  String fileNames) {
        String codedfilename = null;
        try {
            String agent = request.getHeader("USER-AGENT");
            if (null != agent && agent.indexOf("MSIE") > -1 || null != agent
                    && agent.indexOf("Trident") > -1) {// ie
                String name = java.net.URLEncoder.encode(fileNames, "UTF8").replaceAll("\\+", "%20");
                codedfilename = name;
            } else {// 火狐,chrome等

                codedfilename = new String(fileNames.getBytes("UTF-8"),
                        "iso-8859-1");
            }
        } catch (Exception e) {
            logger.error("文件名称编码出错", e);
        }
        return codedfilename;
    }
}
